import 'package:flutter/material.dart';
import 'package:p_location/common/constant/sp_key.dart';
import 'package:p_location/common/res/common_res.dart';
import 'package:p_location/common/widget/no_result_widget.dart';
import 'package:p_location/common/widget/search_bar.dart';
import 'package:p_location/map/constant/map_http_url.dart';
import 'package:p_location/map/res/search_person_detail.dart';
import 'package:p_location/map/res/search_person_info.dart';
import 'package:p_location/map/res/search_person_res.dart';
import 'package:p_location/map/widget/button_item.dart';
import 'package:p_location/map/widget/search_person_item.dart';
import 'package:p_location/net/dio_http_client.dart';
import 'package:p_location/net/net_constants.dart';
import 'package:p_location/net/net_listener_impl.dart';
import 'package:dio/dio.dart';
import 'package:p_location/utils/shared_preferences_util.dart';
import 'package:p_location/utils/string_util.dart';
import 'dart:convert';

class PageSearchPerson extends StatefulWidget {
  final bool isFromRealTime;

  PageSearchPerson(this.isFromRealTime);

  @override
  _PageSearchPersonState createState() => _PageSearchPersonState();
}

class _PageSearchPersonState extends State<PageSearchPerson> {
//  List<String> _list = [
//    '李二蛋 30485037t0035',
//    '大货车 345436',
//    '王绿绿 3453456',
//    '刘大头 5353',
//    '马头头 324',
//    '店小二 23453534',
//    '马化腾 343534',
//    '粑粑 345345',
//    '福牛哥 45434535',
//    '藏海花 4545'
//  ];

  List<SearchPersonDetail> _detailList;

  String errorMsg = "";

  List<Widget> _generateList() {
    return _searchHistroys
        .map((item) => ButtonItem(
              text: '${item.name} ${item.sn}',
              onTap: () {
                cacheSearchItem(item);
                Navigator.pop(context, item);
              },
            ))
        .toList();
  }

  List<SearchPersonDetail> _searchHistroys = [];

  String keyWord;

  @override
  void initState() {
    super.initState();
    readCache();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _getSearchAppBar(context),
      body: Stack(
        children: [
//          Column(
//            children: [
//              Row(
//                mainAxisAlignment: MainAxisAlignment.spaceBetween,
//                children: [
//                  GestureDetector(
//                    onTap: () {
//                      print("34");
//                      showDialogFunction();
//                    },
//                    child: Container(
//                      margin: EdgeInsets.only(left: 12),
//                      child: Text(
//                        "历史搜索记录",
//                        style: TextStyle(color: Color.fromRGBO(0, 0, 0, 0.5)),
//                      ),
//                    ),
//                  ),
//                  IconButton(
//                      onPressed: () {
//                        showDialogFunction();
//                      },
//                      icon: Icon(Icons.delete_outline))
//                ],
//              ),
//              Padding(
//                child: Container(
//                  width: MediaQuery.of(context).size.width,
////                  color:Colors.red,
//                  child: Wrap(
//                      children: _generateList(),
//                      spacing: 8,
//                      runSpacing: 10,
//                      alignment: WrapAlignment.start,
//                      runAlignment: WrapAlignment.end),
//                ),
//                padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
//              )
//            ],
//          ),
          Offstage(
            offstage: _detailList == null || StringUtil.isEmpty(keyWord),
            child: Container(
              color: Color.fromRGBO(0, 0, 0, 0.2),
              child: StringUtil.isNotEmpty(errorMsg)
                  ? _exceptionView
                  : ListView.separated(
                  separatorBuilder: (context, index) {
                    return Divider(
                      color: Colors.grey,
                      height: 0.4,
                    );
                  },
                  itemCount: _detailList?.length ?? 0,
                  itemBuilder: (BuildContext context, int index) {
                    return SearchPersonItem(
                        widget.isFromRealTime, _detailList[index], () {
                      print(_detailList[index].name);
                      print(_detailList[index].toString());

                      cacheSearchItem(_detailList[index]);

//                            Map<String, String> map = Map();
//                            map['searchHistory'] =
//                                "[${_detailList[index].toString()}]";
//                            SharedPreferenceHelp.save(map);

                      Navigator.pop(context, _detailList[index]);
                    });
                  }),
            ),
          )
        ],
      ),
    );
  }

  get _exceptionView => Container(
        color: Colors.white,
        child: NoResultWidget('images/img_no_accident.png', errorMsg),
      );

  _getSearchAppBar(context) {
    return SearchBar(
      hideLeft: false,
      hint: '请输入姓名/定位卡号/车牌',
      leftButtonClick: _pop,
      rightButtonClick: searchRefresh,
      onChanged: _onKeyWordChanged,
    );
  }

  _pop() {
    Navigator.pop(context);
  }

  void _onKeyWordChanged(String value) {
    keyWord = value;
    if (StringUtil.isNotEmpty(keyWord)) {
      _requestSearchPerson();
    } else {
      setState(() {
        _detailList = null;
        errorMsg = "";
      });
    }
  }

  void searchRefresh() {}

  _requestSearchPerson() async {
    _detailList = null;
    Map<String, dynamic> params = {};
//    params["keyword"] = keyWord;
    await DioHttpClient.requestPost(
        context,
        '${MapHttpUrl.PEOPLE_INFO_SEARCH_URL}?keyword=$keyWord',
        params,
        NetListenerImpl((Response response) {
          if (response != null && response.data != null) {
            SearchPersonRes res = SearchPersonRes.fromJson(response.data);
            _detailList = [];
            if (res != null && res.data != null) {
              SearchPersonInfo searchPersonInfo = res.data;
              setState(() {
                if (searchPersonInfo != null) {
                  if (searchPersonInfo.employeeList != null) {
                    _detailList.addAll(searchPersonInfo.employeeList);
                  }
                  if (searchPersonInfo.guestList != null) {
                    _detailList.addAll(searchPersonInfo.guestList);
                  }
                  if (searchPersonInfo.workerList != null) {
                    _detailList.addAll(searchPersonInfo.workerList);
                  }
                  if (searchPersonInfo.innerCarList != null) {
                    _detailList.addAll(searchPersonInfo.innerCarList);
                  }
                  if (searchPersonInfo.outerCarList != null) {
                    _detailList.addAll(searchPersonInfo.outerCarList);
                  }
                }
              });

              print('取到了${_detailList.length}');
              if (_detailList.length == 0) {
                errorMsg = "查无结果";
              } else {
                errorMsg = "";
              }
            }
          }
        }, (CommonRes errorRes) {
          setState(() {
            _detailList = [];
            errorMsg = errorRes?.msg ?? "发生错误";
          });
        }));
  }

  void showDialogFunction() async {
    print("234");
    bool isSelect = await showDialog<bool>(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: Text("温馨提示"),
          //title 的内边距，默认 left: 24.0,top: 24.0, right 24.0
          //默认底部边距 如果 content 不为null 则底部内边距为0
          //            如果 content 为 null 则底部内边距为20
          titlePadding: EdgeInsets.all(10),
          //标题文本样式
          titleTextStyle: TextStyle(color: Colors.black87, fontSize: 16),
          //中间显示的内容
          content: Text("请确认是否删除全部历史记录?"),
          //中间显示的内容边距
          //默认 EdgeInsets.fromLTRB(24.0, 20.0, 24.0, 24.0)
          contentPadding: EdgeInsets.all(10),
          //中间显示内容的文本样式
          contentTextStyle: TextStyle(color: Colors.black54, fontSize: 14),
          //底部按钮区域
          actions: <Widget>[
            TextButton(
              child: Text("取消"),
              onPressed: () {
//                关闭 返回 false
                Navigator.of(context).pop(false);
              },
            ),
            FlatButton(
              child: Text("确认"),
              onPressed: () {
                //关闭 返回true
                SharedPreferenceHelp.remove(SPKey.SEARCH_HISTORY_KEY).then((value) {
                  setState(() {
                    _searchHistroys = [];
                  });
                  Navigator.of(context).pop(true);
                });
              },
            ),
          ],
        );
      },
    );

    print("弹框关闭 $isSelect");
  }

  showAlertDialog(BuildContext context) {
    //设置按钮
    Widget okButton = FlatButton(
      child: Text("OK"),
      onPressed: () {},
    );

    //设置对话框
    AlertDialog alert = AlertDialog(
      title: Text("提示"),
      content: Text("请确认是否清除全部历史记录?"),
      actions: [
        okButton,
      ],
    );

    //显示对话框
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return alert;
      },
    );
  }

  _getSnInfoList() async {
    Map<String, dynamic> params = {};
    await DioHttpClient.requestPost(context, MapHttpUrl.PEOPLE_INFO_SEARCH_URL,
        params, NetListenerImpl(onSuccess, onError),
        contentType: NetConstants.POST_TYPE_FORM);
  }

  cacheSearchItem(SearchPersonDetail item) {
    print("开始读");
    SharedPreferenceHelp.read(SPKey.SEARCH_HISTORY_KEY).then((value) {
      bool isExist = false;
      print("独处了");
      print(value);
//      if (StringUtil.isNotEmpty(value)) {
      print("转换");
      List<SearchPersonDetail> details = [];
      List<dynamic> list = [];
      if (StringUtil.isNotEmpty(value)) {
        list = json.decode(value);
      }
      if (list != null) {
        print('list的size${list.length}');

        list.forEach((element) {
          print(element);
          SearchPersonDetail e = SearchPersonDetail(
              id: element["id"],
              name: element["name"],
              sn: element["sn"],
              updateTime: element["updateTime"]);
          print("--=-=");
          print(e);
          if (e.id == item.id) {
            isExist = true;
            e.updateTime = DateTime.now().microsecondsSinceEpoch;
          }
          print('生成前${details.length}');
          details.add(e);
        });
      }
      if (!isExist) {
        item.updateTime = DateTime.now().microsecondsSinceEpoch;
        details.add(item);
      }

      print('生成后${details.length}');
      //查询生成的
      print('查询生成的${details.length}');
      details
          .sort((a, b) => ((b?.updateTime ?? 0).compareTo(a?.updateTime ?? 0)));
      details.forEach((element) {
        print(element);
      });
      print(details.toString());

      Map<String, String> params = {};
      params[SPKey.SEARCH_HISTORY_KEY] = details.toString();
      SharedPreferenceHelp.save(params);
//      } else {
//        print(json.encode(item));
//      }
    });
  }

  readCache() {
    print("开始读");
    SharedPreferenceHelp.read(SPKey.SEARCH_HISTORY_KEY).then((value) {
      print("独处了");
      print(value);
//      if (StringUtil.isNotEmpty(value)) {
      print("转换");
      List<dynamic> list = [];
      if (StringUtil.isNotEmpty(value)) {
        list = json.decode(value);
      }
      if (list != null) {
        print('list的size${list.length}');
        list.forEach((element) {
          print(element);
          SearchPersonDetail e = SearchPersonDetail(
              id: element["id"],
              name: element["name"],
              sn: element["sn"],
              updateTime: element["updateTime"]);
          print("--=-=");
          print(e);
          _searchHistroys.add(e);
        });
        setState(() {});
      }
    });
  }

  onSuccess(response) {}

  onError(errorRes) {}
}
